import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import store from './store'

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)


const _this = new Vue({
  store
})

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/merchant/index', '/merchant/bank', '/merchant/principal', '/merchant/leader', '/merchant/success' ] 

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) { // has token
    if (to.path === '/login') { // to login
      next({ path: '/index' }) // redirect index
      NProgress.done()
    } else {
      next() // next()
       _this.$store.dispatch('updateAppSetting', true)
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) { // no token and to login
      next() // next
      let allowBack = true
      if (to.meta.back !== undefined) {
        allowBack = to.meta.back
      }
      if (!allowBack) {
        history.pushState(null, null, location.href)
      }
      _this.$store.dispatch('updateAppSetting', allowBack)
    } else {
      next('/login') // to login
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})